package com.bq.server.configuration;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.bq.server.handler.AESTypeHandler;
import com.bq.server.properties.MybatisPlusSecurityProperties;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.mybatis.spring.annotation.MapperScannerRegistrar;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * mybatis 配置
 */
@Configuration
@EnableTransactionManagement
@ConditionalOnClass(MapperScannerRegistrar.class)
@EnableConfigurationProperties(MybatisPlusSecurityProperties.class)
public class MyBatisConfiguration {


    private final MybatisPlusSecurityProperties securityProperties;

    public MyBatisConfiguration(MybatisPlusSecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    /**
     * 自定义配置,添加 AESTypeHandler 加解密handler
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            AESTypeHandler typeHandler = new AESTypeHandler(securityProperties.getAesKey());
            typeHandlerRegistry.register((Class<String>) null, typeHandler);
        };
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
